//名单导入
/**
 * @openapi
 * tags:
 * - name: name_list
 *   description: 名单
 */
const router = require("express-promise-router")();

const path=require('path');
const multer  = require('multer');
const config=require("../../config/config");
const template_file = config.template_file;
const tmp_uploads_dir=config.tmp_uploads_dir; //存放临时上传的文件。导入完成后就可以删除。不做hash处理
const upload = multer({ dest: tmp_uploads_dir });
//console.log('tmp_uploads_dir',tmp_uploads_dir);


const NameListService = require("../../services/name_list");
const LogService = require("../../services/log");

/**
 * @openapi
 * /teacher/name_list/import:
 *   post:
 *     tags:
 *     - name_list
 *     summary: 导入名单
 *     requestBody:
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               file:
 *                 type: string
 *                 format: binary
 *               dataColumnNumber:
 *                 type: number
 *               firstDataRowNumber:
 *                 type: number
 *     responses:
 *       200:
 *         description: 返回创建的名单数量与更新的名单数
 */
router.post('/import',upload.single('file'), async function(req, res) {
    let {dataColumnNumber=1,firstDataRowNumber=2}=req.body;
    const result=await NameListService.importNameListFromExcelFile(req.file.path,dataColumnNumber,firstDataRowNumber);
    if(result.error){
        return res.status(400).send(result);
    }else{
        LogService.addLog(req.session.user,"名单",`上传文件导入名单`);
        return res.json(result);
    }
});


/**
 * @openapi
 * /teacher/name_list/add:
 *   post:
 *     tags:
 *     - name_list
 *     summary: 创建名单
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               usernames:
 *                  type: array
 *                  items:
 *                      type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/add', async function(req, res) {
    const user=req.session.user;
    const owner=user.username;
    let {name,usernames}=req.body;
    const result=await NameListService.add(name,usernames,owner);
    LogService.addLog(user,"名单",`添加名单${name}`);
    return res.json(result);
});

/**
 * @openapi
 * /teacher/name_list/remove:
 *   post:
 *     tags:
 *     - name_list
 *     summary: 删除名单
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               id:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/remove', async function(req, res) {
    let {id}=req.body;
    const result=await NameListService.remove(id);
    LogService.addLog(req.session.user,"名单",`删除名单${id}`);
    return res.json(result);
});


/**
 * @openapi
 * /teacher/name_list/update:
 *   post:
 *     tags:
 *     - name_list
 *     summary: 名单更新
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               id:
 *                 type: string
 *               key:
 *                 type: string
 *               value:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/update', async function(req, res) {
    let {id,key,value}=req.body;
    const result=await NameListService.update(id,key,value);
    LogService.addLog(req.session.user,"名单",`更新名单${id}`);
    return res.json(result);
});

/**
 * @openapi
 * /teacher/name_list/add_user  :
 *   post:
 *     tags:
 *     - name_list
 *     summary: 添加成员到名单中
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               id:
 *                 type: string
 *               username:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回修改的名单
 */
router.post('/add_user', async function(req, res) {
    let {id,username}=req.body;
    const result=await NameListService.add_user(id,username);
    LogService.addLog(req.session.user,"名单",`添加名单成员：${id}:${username}`);
    return res.json(result);
});

/**
 * @openapi
 * /teacher/name_list/remove_user  :
 *   post:
 *     tags:
 *     - name_list
 *     summary: 移除名单中的成员
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               id:
 *                 type: string
 *               username:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回修改的名单
 */
router.post('/remove_user', async function(req, res) {
    let {id,username}=req.body;
    const result=await NameListService.remove_user(id,username);
    LogService.addLog(req.session.user,"名单",`移除名单成员：${id}:${username}`);
    return res.json(result);
});

/**
 * @openapi
 * /teacher/name_list/set_followers  :
 *   post:
 *     tags:
 *     - name_list
 *     summary: 设置名单追踪
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               nameListId:
 *                 type: string
 *               followerId:
 *                 type: string
 *               followerTable:
 *                 type: string
 *               followerFields:
 *                  type: array
 *                  items:
 *                      type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回修改的名单
 */
router.post('/set_followers', async function(req, res) {
    let {nameListId,followerId,followerTable,followerFields}=req.body;
    const result=await NameListService.setFollowers(nameListId,followerId,followerTable,followerFields);
    LogService.addLog(req.session.user,"名单",`设置名单追踪${nameListId}`);
    return res.json(result);
});


/**
 * @openapi
 * /teacher/name_list/unset_followers  :
 *   post:
 *     tags:
 *     - name_list
 *     summary: 取消名单追踪
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               nameListId:
 *                 type: string
 *               followerId:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回修改的名单
 */
router.post('/unset_followers', async function(req, res) {
    let {nameListId,followerId}=req.body;
    const result=await NameListService.unsetFollowers(nameListId,followerId);
    LogService.addLog(req.session.user,"名单",`取消名单追踪${nameListId}`);
    return res.json(result);
});


/**
 * @openapi
 * /teacher/name_list/follow_name_list  :
 *   post:
 *     tags:
 *     - name_list
 *     summary: 执行名单跟踪
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               nameListId:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 成功
 */
router.post('/follow_name_list', async function(req, res) {
    let {nameListId}=req.body;
    const result=await NameListService.followNameList(nameListId);
    LogService.addLog(req.session.user,"名单",`执行名单追踪${nameListId}`);
    return res.json(result);
});


/**
 * @openapi
 * /teacher/name_list/import_member/check_file:
 *   post:
 *     tags:
 *     - name_list
 *     summary: 导入成员第一步，检查excel文件
 *     requestBody:
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               file:
 *                 type: string
 *                 format: binary
 *               nameRowNumber:
 *                 type: number
 *               firstDataRowNumber:
 *                 type: number
 *               fieldsMapping:
 *                 type: object  例如："{\"学号\":\"username\",\"姓名\":\"showName\",\"专业\":\"subject\",\"班级\":\"eduClass\"}"
 *     responses:
 *       200:
 *         description: 返回JSON文件信息
 */
//从excel文件导入用户，可传递标题行与数据开始行，可以传递一个表头映射对象
router.post('/import_member/check_file', upload.single('file'), async function  (req, res){
    // req.file 是 `users` 文件的信息
    // req.body 将具有文本域数据，如果存在的话
    //req.file.path 是文件路径
    var default_nameRowNumber = 1;
    var default_firstDataRowNumber = 2;
    if(template_file==='users_kmust.xlsx'){
        default_nameRowNumber = 5;
        default_firstDataRowNumber = 6;
    }
    let {nameRowNumber=default_nameRowNumber,firstDataRowNumber=default_firstDataRowNumber,fieldsMapping}=req.body;
    if(fieldsMapping){
        fieldsMapping=JSON.parse(fieldsMapping);
    }
    //console.log("fieldsMapping",fieldsMapping);
    //检查Excel文件是否合乎格式
    const result=await NameListService.checkExcelFile(req.file.path,nameRowNumber,firstDataRowNumber,fieldsMapping);
    if(result.error){
        return res.status(400).send({"error":result.error});
    }else{
        return res.json(result);
    }
});

/*
{
  "filePath": "C:\\x_项目\\lims_v5\\tmp_uploads\\5ab1bed9b851ff3be2eec9cfc7023b73",
  "nameRowNumber": 6,
  "firstDataRowNumber": 7,
  "fieldsMapping": {"学号":"username"}
}
* */
/**
 * @openapi
 * /teacher/name_list/import_member/confirm_file:
 *   post:
 *     tags:
 *     - name_list
 *     summary: 导入成员第二步，确认导入excel文件
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               filePath:
 *                 type: string
 *               nameRowNumber:
 *                 type: number
 *               firstDataRowNumber:
 *                 type: number
 *               fieldsMapping:
 *                 type: object
 *               id:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回有几条重复，几条新增
 */
router.post('/import_member/confirm_file',  async function  (req, res){
    //从客户端取得要导入的文件路径，由check_file给出
    var default_nameRowNumber = 1;
    var default_firstDataRowNumber = 2;
    if(template_file==='users_kmust.xlsx'){
        default_nameRowNumber = 5;
        default_firstDataRowNumber = 6;
    }
    let {nameRowNumber=default_nameRowNumber,firstDataRowNumber=default_firstDataRowNumber,filePath,fieldsMapping,id}=req.body;
    if(fieldsMapping){
        fieldsMapping=JSON.parse(fieldsMapping);
    }
    //导入到数据库
    const result=await NameListService.importExcelFile(filePath,nameRowNumber,firstDataRowNumber,fieldsMapping,id);
    LogService.addLog(req.session.user,"名单",`导入成员到名单中`);
    res.json(result);
});
module.exports = router;